using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Npgsql;

namespace DbaseInfo
{
    public class DatabaseInfo
    {
        private String _conn_string = null;
        private NpgsqlConnection _conn = null;
        private List<TableInfo> _tables = new List<TableInfo>();

        /// <summary>
        /// Class constructor
        /// </summary>
        /// <param name="connection_string">Valid conn string</param>
        public DatabaseInfo(String connection_string)
        {
            // Attempt to connect to database & gather info ...
            try
            {
                _conn_string = connection_string;
                _conn = new NpgsqlConnection(connection_string);
                _conn.Open();
                _conn.Close();

                // Retrieve info on table_list & fields 
                GetTableList();
            }
            catch (Exception ex)
            {
                _conn = null;
                Console.WriteLine(ex.Message);
            }
        }

        #region Public Properties

        public int TableCount
        {
            get { return _tables.Count; }
        }

        public Boolean GotDatabaseInformation
        {
            get { return (TableCount > 0 ? true : false); }
        }

        public TableInfo[] Tables        
        {
            get { return _tables.ToArray() ; }
        }

        #endregion

        #region Private Members
        
        /// <summary>
        /// Retrieves a list of table_list for selected database
        /// </summary>
        private void GetTableList()
        {
            NpgsqlCommand command;
            NpgsqlDataReader dr;

            _conn.Open();

            try
            {
                command = new NpgsqlCommand("select tablename from pg_tables where schemaname LIKE 'public' order by tablename ASC", _conn);
                dr = command.ExecuteReader();

                // For each table ...
                while (dr.Read())
                {
                    // ... Append it to the table list 
                    _tables.Add(new TableInfo((string)dr[0], _conn_string));
                }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Ensure conn is ALWAYS closed
                _conn.Close();
            }
        }
        
        #endregion
    }
}
